package org.example.system.controller;

import org.example.system.entity.ScenicSpot;
import org.example.system.service.ScenicSpotService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/scenic")
public class ScenicSpotController {
    @Autowired
    private ScenicSpotService scenicSpotService;

    @GetMapping
    public List<ScenicSpot> list(@RequestParam(required = false) String name) {
        if (name != null && !name.isEmpty()) {
            return scenicSpotService.findByName(name);
        }
        return scenicSpotService.findAll();
    }

    @GetMapping("/{id}")
    public ScenicSpot detail(@PathVariable Long id) {
        return scenicSpotService.findById(id);
    }

    @PostMapping
    public Map<String, Object> add(@RequestBody ScenicSpot spot) {
        Map<String, Object> result = new java.util.HashMap<>();
        int row = scenicSpotService.add(spot);
        result.put("success", row > 0);
        result.put("message", row > 0 ? "添加成功" : "添加失败");
        return result;
    }

    @PutMapping("/{id}")
    public Map<String, Object> update(@PathVariable Long id, @RequestBody ScenicSpot spot) {
        spot.setId(id);
        Map<String, Object> result = new java.util.HashMap<>();
        int row = scenicSpotService.update(spot);
        result.put("success", row > 0);
        result.put("message", row > 0 ? "修改成功" : "修改失败");
        return result;
    }

    @DeleteMapping("/{id}")
    public Map<String, Object> delete(@PathVariable Long id) {
        Map<String, Object> result = new java.util.HashMap<>();
        int row = scenicSpotService.delete(id);
        result.put("success", row > 0);
        result.put("message", row > 0 ? "删除成功" : "删除失败");
        return result;
    }

    @GetMapping("/byName")
    public ScenicSpot getByName(@RequestParam String name) {
        List<ScenicSpot> list = scenicSpotService.findByName(name);
        return (list != null && !list.isEmpty()) ? list.get(0) : null;
    }
} 